package vip.redme.memory.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import vip.redme.memory.pojo.dto.UserDto;
import vip.redme.memory.pojo.entity.User;
import vip.redme.memory.response.Result;
import vip.redme.memory.service.AuthService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: SherryZhao
 * @Date: 2021/8/8 20:59
 */

@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @PostMapping("/login")
    public Result login(@RequestBody User user, HttpServletResponse response) {
        UserDto dto = authService.login(user);
        //设置cookies
        Cookie cookie = new Cookie("token", dto.getToken());
        response.addCookie(cookie);
        return Result.success(dto);
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user, HttpServletResponse response) {
        UserDto dto = authService.register(user);
        //设置cookies
        Cookie cookie = new Cookie("token", dto.getToken());
        response.addCookie(cookie);
        return Result.success(dto);
    }

    @GetMapping("/autoLogin")
    public Result loginByToken(@RequestParam("token") String token, HttpServletResponse response) {
        UserDto dto = authService.loginByToken(token);
        //设置cookies
        Cookie cookie = new Cookie("token", dto.getToken());
        response.addCookie(cookie);
        return Result.success(dto);
    }

}
